package com.example.springsecurity.config;

import com.example.springsecurity.filter.JwtAuthenticationFilter;
import jakarta.annotation.Resource;


import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.AuthorizationFilter;

@Configuration
public class SecurityConfig {
    @Resource
    private JwtAuthenticationFilter jwtAuthenticationFilter;//实际注册的是自定义的JwtAuthenticationFilter
    @Resource
    private UserDetailsService userDetailsService;//实际注册的是自定义的UserDetailsServiceImpl


    /*@Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }*/


    @Bean
    public AuthenticationManager authenticationManager() {//自定义authenticationManager,是发起认证的源头
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);
        return new ProviderManager(provider);
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {//自定义filterChain
        http
                .formLogin(form->form.disable())//禁用默认页面，使用自定义的result响应体，不跳转页面
               // .sessionManagement(session->session.disable())//禁用session(存在安全上下文中了)
                .csrf(csrf->csrf.disable())//禁用csrf防火墙
                .cors(Customizer.withDefaults())//允许跨域访问，禁用浏览器限制
                .addFilterBefore(jwtAuthenticationFilter, AuthorizationFilter.class);
        return http.build();
    }
}
